package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.response.pc.QueryWishResponse
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext

// 许愿操作结果
sealed class WishOperationResult {
    object Continue : WishOperationResult() // 需要继续
    object Complete : WishOperationResult() // 完成，无需继续
    data class Failure(val error: String) : WishOperationResult() // 失败
}

// 许愿工作
class WishWork(override val uin: String): BaseWork(uin) {
    
    override val name: String
        get() = "许愿"
    
    override val priority: Int
        get() = 7
    
    private val gameApi by lazy { GameApi() }
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 开始许愿流程，可能需要多次查询和操作
            executeWishFlow()
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 执行许愿流程，包含多次查询和操作
     */
    private suspend fun executeWishFlow(): WorkResult {
        var maxRetries = 5 // 最大重试次数
        var retryCount = 0
        
        while (retryCount < maxRetries) {
            // 查询当前许愿状态
            val queryResult = gameApi.queryWish()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 根据状态执行相应操作，由 processWishResponse 决定是否需要继续
                    val operationResult = processWishResponse(response)
                    
                    when (operationResult) {
                        is WishOperationResult.Continue -> {
                            // 需要继续，进行下一轮查询
                            retryCount++
                        }
                        is WishOperationResult.Complete -> {
                            // 完成，无需继续
                            return WorkResult.Success
                        }
                        is WishOperationResult.Failure -> {
                            // 失败，直接返回失败
                            historyManager.addHistory(name, operationResult.error)
                            return WorkResult.Failure(Exception(operationResult.error), operationResult.error)
                        }
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WorkResult.Failure(Exception(msg), msg)
                }
            )
        }
        
        return WorkResult.Success
    }
    
    /**
     * 处理许愿查询响应
     */
    private suspend fun processWishResponse(response: QueryWishResponse): WishOperationResult {
        var hasOperation = false // 标记是否有操作执行
        
        // 1. 如果可以领许愿奖，则领取
        if (response.fb == 1) {
            hasOperation = true
            val rewardResult = gameApi.getWishReward()
            rewardResult.foldWithApiException(
                onSuccess = { rewardResponse ->
                    historyManager.addHistory(name, rewardResponse.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WishOperationResult.Failure(msg)
                }
            )
        } else if (response.fb == 2) {
            // 只许愿
            hasOperation = true
            val wishResult = gameApi.wish()
            wishResult.foldWithApiException(
                onSuccess = { wishResponse ->
                    historyManager.addHistory(name, wishResponse.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WishOperationResult.Failure(msg)
                }
            )
        }
        
        // 2. 如果可以领宝箱，则领取
        if (response.canChest != 0) {
            val chestResult = gameApi.getWishChest()
            chestResult.foldWithApiException(
                onSuccess = { chestResponse ->
                    historyManager.addHistory(name, chestResponse.getDescription())
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    return WishOperationResult.Failure(msg)
                }
            )
        }
        
        // 根据是否有操作来决定是否需要继续
        return if (hasOperation) {
            WishOperationResult.Continue // 有操作，需要继续查询状态
        } else {
            WishOperationResult.Complete // 无操作，完成
        }
    }
}